<?php

/***************************************************************\
* FILE:		/sys/regionfunctions.inc
* SECTION:	util > region functions
* FUNCTION:	reusable functions for region management
* USES:		sys/formfunctions.inc
* INCLUDES:	sys/inputcheck.inc
* PRODUCES:	
* LAUNCHES:	
\***************************************************************/

include_once('sys/inputcheck.inc');

function region_get_regions() {
	$sqlresult = db_do_query(db_query_select(array(array(), "REGION.*, REGION_TREE.*"), array("REGION INNER JOIN REGION_TREE ON region_id = sub_region", "DUMMY"), 1, "parent_region ASC, name ASC"));
	$rs = array();
	while ($r = db_fetch_array($sqlresult)) {
		$rs[$r['region_id']] = $r;
		$rs[$r['parent_region']]['children'][] = $r['region_id'];
	}
	return $rs;
}

function region_get_region_tree($region_id, $tree=0) {
	if (!$tree)
		$tree = region_get_regions();
	$r = array();
	while ($region_id > 0) {
		$r[] = $tree[$region_id];
		$region_id = $tree[$region_id]['parent_region'];
	}
	return $r;
}

function region_get_regions_kv($insertmode=0, $tree=0) {
	if (!$tree)
		$tree = region_get_regions();
	$k = array();
	$v = array();
	return region_get_regions_kv_aux($insertmode, $tree, $k, $v, 0, 0);
}
function region_get_regions_kv_aux($insertmode, $tree, $keys, $values, $parent, $level) {
	$space = "";
	for ($i = 0; $i < $level; $i++)
		$space .= "&nbsp;&nbsp;&nbsp;&nbsp;";
	reset($tree[$parent]['children']);
	do {
		$id = current($tree[$parent]['children']);
		$keys[] = $id;
		$values[] = $space . $tree[$id]['name'];
		if (is_array($tree[$id]['children']) and count($tree[$id]['children'])) {
			$kv = region_get_regions_kv_aux($insertmode, $tree, $keys, $values, $id, $level+1);
			$keys = $kv['keys'];
			$values = $kv['values'];
		}
		if ($insertmode) {
			$keys[] = "parent" . $id;
			$values[] = $space . "&nbsp;&nbsp;&nbsp;&nbsp;[in {$tree[$id]['name']}]";
		}
	} while (next($tree[$parent]['children']));		
	return array('keys' => $keys, 'values' => $values);
}

function region_format($regio) {
	$str = "";
	if (is_array($regio) and count($regio))
		while ($r = @array_pop($regio))
			$str = "$str > {$r['name']}";
	else
		return "[onbekend]";
	return substr($str, 3);
		
}

function region_is_inside($target, $super, $tree=0) {
	if ($tree == 0)
		$tree = region_get_regions();
	/*echo "<pre>";
	print_r($tree);
	echo "<br/><br/>";*/
	$target = region_get_region_tree($target, $tree);
	//print_r($target);
	while ($r = array_shift($target)) {
		//echo "<li>{$r['name']} ({$r['region_id']}) ?= $super";
		if ($super == $r['region_id'])
			return 1;
	}
	return 0;
}

?>